<script>
    // 类方法(静态方法) allSettled

    // 创建三个Promise
    const p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("p1 resolve")
            // reject("p1 reject error")
        }, 3000)
    })
    const p2 = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("p2 resolve")
            // reject("p2 reject error")
        }, 2000)
    })
    const p3 = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("p3 resolve")
        }, 5000)
    })

    function isPromise(val) {
        return typeof val.then === "function"
    }
    Promise.allSettled = function (promises) {
        return new Promise((resolve, reject) => {
            let arr = [];
            let times = 0;
            let setData = (index, data) => {
                arr[index] = data;
                if (++times === promises.length) {
                    resolve(arr)
                }
            }

            for (let i = 0; i < promises.length; i++) {
                let current = promises[i];
                if (isPromise(current)) {
                    current.then(data => {
                        setData(i, { status: 'fulfilled', value: data })
                    }, err => {
                        setData(i, { status: 'rejected', value: err })
                    })
                } else {
                    setData(i, { status: 'rejected', value: current })
                }
            }
        })
    }


    // allSettled  获取所有的promise的结果，不管成功还是失败
    Promise.allSettled([p1, p2, p3]).then(res => {
        console.log("all settled:", res)
    })
</script>